#include "matrix.h"
#include "stdlib.h"

Matrix* createMatrix() {
	Matrix* ret = malloc(sizeof(Matrix));
	ret->size = 1;
	ret->data = malloc( sizeof(NUMTYPE) * ret->size * ret->size );
	return ret;
}

NUMTYPE* indexMatrix(Matrix* m, int i, int j) {
	
	if (i+1 > m->size || j+1 > m->size) {
		redim(m, (i > j ? i : j) + 1 );
	}
	
	return m->data + i*m->size + j ;
}

void redim(Matrix* m, int newsize) {
	NUMTYPE* newdata = malloc( sizeof(NUMTYPE) * newsize * newsize );
	
	int i;
	int j;
	// copiar los datos
	for (i = 0; i < newsize; i++) {
		for (j = 0; j < newsize; j++) {
			if (i < m->size && j < m->size) {
				newdata[i*newsize+j] = m->data[i*m->size+j];
			} else {
				newdata[i*newsize+j] = 0.0;
			}
		}
	}
	
	NUMTYPE *olddata = m->data;
	m->data = newdata;
	m->size = newsize;
	
	free(olddata);
}

void destroyMatrix(Matrix* m) {
	free(m->data);
	free(m);
}
